/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "IndexBuffer.h"
#include "Hardware.h"
#include "VertexBuffer.h"
#include <logs/Log.h>
#include <Gluck.h>
#include "Creator.h"
#include <math/utl.h>

namespace liba
{
namespace lib3d
{
namespace hard
{
namespace marmalade
{

IndexBuffer::IndexBuffer()
:	indices_count(0),
	valid_flag(false)
{
	glGenBuffers( 1, &index_buffer );
	if ( !index_buffer )
		THROW(Gluck(__FUNCTION__, "create_internal_index_buffer() failed"));
}
	
IndexBuffer::~IndexBuffer()
{
	valid_flag = false;

	VertexBuffer::reset_cached_buffer();
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	if( index_buffer )
		glDeleteBuffers( 1, &index_buffer );
	index_buffer = 0;
}

bool IndexBuffer::is_valid()const
{
	return valid_flag;
}
	
bool IndexBuffer::update( const int * indices, int indices_count )
{
	SimpleArray<unsigned short> indices_short(indices_count);
	for(int i = 0; i < indices_count; ++i)
	{
		indices_short[i] = indices[i];
	}
	
	VertexBuffer::reset_cached_buffer();
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_count * 2, indices_short.data(), GL_STATIC_DRAW);
	
	this->indices_count = indices_count;
	valid_flag = true;
	
	return true;
}
	
bool IndexBuffer::render( int index_pos, int primitive_count, int vertex_pos, int vertex_count )
{
	return true;
}
	
} // namespace marmalade
} // namespace hard
} // namespace lib3d
} // namespace liba
using namespace liba;

